package com.zhicheng.service.impl;

import com.zhicheng.exception.BaseException;
import com.zhicheng.mapper.GoodMapper;
import com.zhicheng.mapper.ShoppingCartMapper;
import com.zhicheng.pojo.ShoppingCart;
import com.zhicheng.pojo.dto.ShoppingCartDTO;
import com.zhicheng.pojo.vo.GoodVO;
import com.zhicheng.pojo.vo.OrderSummaryVO;
import com.zhicheng.service.ShoppingCartService;
import com.zhicheng.utils.ThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;

@Service
@Slf4j
public class ShoppingCartServiceImpl implements ShoppingCartService {

    @Autowired
    private ShoppingCartMapper shoppingCartMapper;

    @Autowired
    private GoodMapper goodMapper;

    @Override
    public void addShoppingCart(ShoppingCartDTO shoppingCartDTO) {
        ShoppingCart shoppingCart = new ShoppingCart();
        BeanUtils.copyProperties(shoppingCartDTO,shoppingCart);

        Long userId = ThreadLocalUtil.getCurrentId();
        shoppingCart.setUserId(userId);

        List<ShoppingCart> list = shoppingCartMapper.list(shoppingCart);


        if (list != null && list.size() > 0){
            throw new BaseException("商品已在购物车");
        }else {
            Long goodId = shoppingCart.getGoodId();
            GoodVO good = goodMapper.getGoodsById(goodId);
            shoppingCart.setName(good.getName());
            shoppingCart.setDesc(good.getDesc());
            shoppingCart.setImgUrl(good.getPicture());
            shoppingCart.setPrice(good.getPrice());
            shoppingCart.setCreateTime(LocalDateTime.now());
            shoppingCartMapper.insert(shoppingCart);
        }
    }

    @Override
    public List<ShoppingCart> showShoppingCart() {
        Long userId = ThreadLocalUtil.getCurrentId();
        ShoppingCart shoppingCart = ShoppingCart.builder()
                .userId(userId)
                .build();
        List<ShoppingCart> list = shoppingCartMapper.list(shoppingCart);
        return list;
    }

    @Override
    public void deleteShoppingCart(ShoppingCartDTO shoppingCartDTO) {
        Long userId = ThreadLocalUtil.getCurrentId();
        ShoppingCart shoppingCart = ShoppingCart.builder()
                .userId(userId)
                .goodId(shoppingCartDTO.getGoodId())
                .build();
        List<ShoppingCart> list = shoppingCartMapper.list(shoppingCart);

        if (list != null && list.size() > 0){
            ShoppingCart cart = list.get(0);
           shoppingCartMapper.deleteById(cart.getId());
        }else {
            throw new BaseException("商品不在购物车");
        }
    }

    @Override
    public void updateShoppingCart(List<ShoppingCart> shoppingCarts) {
        for (ShoppingCart cart : shoppingCarts) {
           shoppingCartMapper.updateCart(cart);
        }

    }

}
